#include <func.h>
#define n 10000000
int main(int argc,char **argv)
{
    int shmid = shmget(IPC_PRIVATE,4096,IPC_CREAT|0600);
    ERROR_CHECK(shmid,-1,"shmget");

    int *i = (int *)shmat(shmid,NULL,0);
    ERROR_CHECK(i,(int *)-1,"shmat");

    int semId =semget(1000,1,IPC_CREAT|0600);
    ERROR_CHECK(semId,-1,"semget");

    int ret = semctl(semId,0,SETVAL,1);
    ERROR_CHECK(ret,-1,"semctl");

    struct sembuf sopp,sopv;
    sopp.sem_num = 0;
    sopp.sem_op = -1;
    sopp.sem_flg = SEM_UNDO;
    
    sopv.sem_num = 0;
    sopv.sem_op = 1;
    sopv.sem_flg = SEM_UNDO;


    if(!fork())
    {
        for(int j = 0;j<n;++j)
        {
             semop(semId,&sopp,1);
             *i+=1;
             semop(semId,&sopv,1);
        }
    }
    else
    {
        printf("calculating...\n");
        for(int k = 0;k<n;++k)
        {
            semop(semId,&sopp,1);
            *i+=1;
            semop(semId,&sopv,1);
        }
        wait(NULL);
        printf("%d\n",*i);
        shmctl(shmid,IPC_RMID,NULL);
        semctl(semId,IPC_RMID,0);
    }

    return 0;
}

